package midway.madness.post.image;

import java.io.IOException;

import midway.madness.R;
import midway.madness.utils.ApplicationEx;
import midway.madness.utils.SplashScreen;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ImageView;

public class ImageViewerActivity extends Activity{

	private SplashScreen splash;
	private ImageStateSaver saver;
	private Bitmap bmap = null;
	
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		splash = new SplashScreen(ImageViewerActivity.this);
		splash.showSplash();
		
		setContentView(R.layout.picture_viewer);
		
		new DownloadBitmap().execute(new Void[0]);
	}
	
	public Object onRetainNonConfigurationInstance(){
		ImageStateSaver saver = new ImageStateSaver();
		saver.setBmap(bmap);
		return saver;
	}
	
	private class DownloadBitmap extends AsyncTask<Void, Void, Void>{

		@Override
		protected Void doInBackground(Void... params) {			
			saver = (ImageStateSaver) getLastNonConfigurationInstance();
			if (null != saver){
				bmap = saver.getBmap();
			}else{
				Bundle extras = getIntent().getExtras();
				String url = extras.getString("url");
				
				try {
					bmap = ((ApplicationEx) getApplication()).loadBitmap(url);
				} catch (IOException e) {
					splash.removeSplash();
					AlertDialog dialog = ((ApplicationEx) getApplication()).handleError(ImageViewerActivity.this, "bitmap");
					dialog.setOnDismissListener(new OnDismissListener() {
						
						public void onDismiss(DialogInterface dialog) {
							ImageViewerActivity.this.finish();
						}
					});
					return null;
				}
			}
			return null;
		}
		
		protected void onPostExecute(Void v){
			if (null != bmap){
				ImageView iv = (ImageView) findViewById(R.id.pic_view);
				iv.setImageBitmap(bmap);
				iv.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
				splash.removeSplash();
			}
		}
		
	}
}
